<template>
  <div class="space-y-8">
    <!-- 分类选择 -->
    <div class="space-y-4">
      <div class="space-y-1">
        <h3 class="text-base font-medium text-slate-700 flex items-center">
          文章分类 <span class="text-rose-500 ml-1">*</span>
        </h3>
        <p class="text-sm text-slate-500">
          选择一个最适合你文章内容的分类。好的分类有助于读者发现你的文章。
        </p>
      </div>
      
      <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
        <div 
          v-for="category in categories" 
          :key="category.id"
          class="flex items-center p-3 rounded-lg border cursor-pointer transition-colors"
          :class="[
            selectedCategoryId === category.id 
              ? 'bg-slate-50 border-slate-300 shadow-sm' 
              : 'border-slate-200 hover:bg-slate-50'
          ]"
          @click="selectCategory(category.id)"
        >
          <div class="flex-shrink-0 flex items-center justify-center w-9 h-9 rounded-md bg-slate-100 text-slate-600 mr-3">
            <span v-html="getCategoryIcon(category)"></span>
          </div>
          <div class="flex-1 min-w-0">
            <div class="font-medium text-slate-700 truncate">{{ category.name }}</div>
            <div class="text-xs text-slate-500" v-if="category.posts_count">
              {{ category.posts_count }} 篇文章
            </div>
          </div>
          <div v-if="selectedCategoryId === category.id" class="flex-shrink-0 text-slate-600 ml-2">
            <CheckCircleIcon class="w-5 h-5" />
          </div>
        </div>
      </div>
    </div>
    
    <!-- 标签选择 -->
    <div class="space-y-4">
      <div class="space-y-1">
        <h3 class="text-base font-medium text-slate-700 flex items-center">
          文章标签 <span class="text-slate-400 font-normal ml-1">(可选)</span>
        </h3>
        <p class="text-sm text-slate-500">
          添加3-5个标签，帮助读者更好地理解你的文章内容。
        </p>
      </div>
      
      <div class="space-y-3">
        <div class="relative">
          <input 
            v-model="tagSearchQuery" 
            type="text" 
            placeholder="搜索标签或输入新标签名后回车创建..."
            class="w-full px-3 py-2 pl-9 pr-8 rounded-md border border-slate-300 text-slate-700 placeholder-slate-400 focus:outline-none focus:ring-1 focus:ring-slate-500 focus:border-slate-500"
            @input="searchTags"
            @focus="showTagDropdown = true"
            @blur="handleInputBlur"
            @keydown.enter.prevent="handleTagEnter"
            @keydown.down.prevent="(e) => handleTagNavigation(1, e)"
            @keydown.up.prevent="(e) => handleTagNavigation(-1, e)"
            @keydown.esc="showTagDropdown = false"
          />
          <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
            <MagnifyingGlassIcon class="w-4 h-4 text-slate-400" />
          </div>
          
          <!-- 下拉箭头 -->
          <div class="absolute inset-y-0 right-0 pr-3 flex items-center pointer-events-none">
            <ChevronDownIcon 
              class="w-4 h-4 text-slate-400 transition-transform"
              :class="{ 'rotate-180': showTagDropdown }"
            />
          </div>
          
          <!-- 下拉列表 -->
          <div 
            v-if="showTagDropdown && (tagSearchQuery || filteredTags.length > 0 || allTags.length > 0)" 
            class="absolute z-50 mt-1 w-full bg-white rounded-md shadow-lg border border-slate-200 max-h-60 overflow-y-auto"
          >
            <!-- 搜索中提示 -->
            <div v-if="tagSearchQuery && isSearchingTags" class="px-3 py-4 text-center text-sm text-slate-500">
              <ArrowPathIcon class="animate-spin h-5 w-5 text-slate-400 mx-auto mb-2" />
              搜索中...
            </div>
            
            <!-- 搜索结果显示 -->
            <div v-else-if="tagSearchQuery && filteredTags.length > 0" class="py-1">
              <div 
                v-for="(tag, index) in filteredTags" 
                :key="tag.id"
                class="flex items-center justify-between px-3 py-2 cursor-pointer transition-colors"
                :class="{ 
                  'bg-slate-100': index === activeTagIndex,
                  'hover:bg-slate-50': index !== activeTagIndex
                }"
                @mousedown.prevent="addTag(tag)"
              >
                <div class="flex items-center gap-2">
                  <span class="text-slate-700 text-sm">{{ tag.name }}</span>
                  <span class="text-xs text-slate-400" v-if="tag.posts_count">
                    ({{ tag.posts_count }})
                  </span>
                </div>
                <CheckIcon v-if="isTagSelected(tag.id)" class="w-4 h-4 text-green-600" />
              </div>
            </div>
            
            <!-- 所有标签列表（当没有搜索内容时） -->
            <div v-else-if="!tagSearchQuery && availableTags.length > 0" class="py-1">
              <div class="px-3 py-2 text-xs font-medium text-slate-500 uppercase tracking-wider border-b border-slate-100">
                所有标签（{{ availableTags.length }}）
              </div>
              <div 
                v-for="(tag, index) in availableTags" 
                :key="tag.id"
                class="flex items-center justify-between px-3 py-2 cursor-pointer transition-colors"
                :class="{ 
                  'bg-slate-100': index === activeTagIndex,
                  'hover:bg-slate-50': index !== activeTagIndex
                }"
                @mousedown.prevent="addTag(tag)"
              >
                <div class="flex items-center gap-2">
                  <span class="text-slate-700 text-sm">{{ tag.name }}</span>
                  <span class="text-xs text-slate-400" v-if="tag.posts_count">
                    ({{ tag.posts_count }})
                  </span>
                </div>
              </div>
            </div>
            
            <!-- 创建新标签选项 -->
            <div 
              v-if="tagSearchQuery && tagSearchQuery.trim().length >= 2 && canCreateNewTag" 
              class="border-t border-slate-200 py-1"
            >
              <div 
                class="flex items-center px-3 py-2 cursor-pointer hover:bg-slate-50 text-sm transition-colors"
                :class="{ 'bg-slate-100': activeTagIndex === filteredTags.length }"
                @mousedown.prevent="createTag()"
              >
                <PlusIcon class="w-4 h-4 text-slate-500 mr-2" />
                <span class="text-slate-600">创建标签 "</span>
                <span class="text-slate-800 font-medium">{{ tagSearchQuery.trim() }}</span>
                <span class="text-slate-600">"</span>
              </div>
            </div>
            
            <!-- 无结果提示 -->
            <div v-else-if="tagSearchQuery && !isSearchingTags && filteredTags.length === 0 && !canCreateNewTag" class="px-3 py-4 text-center text-sm text-slate-500">
              没有找到匹配的标签
            </div>
          </div>
        </div>
        
        <div v-if="selectedTags.length > 0" class="flex flex-wrap gap-2">
          <div 
            v-for="(tag, index) in selectedTags" 
            :key="tag.id || `new-${tag.name}-${index}`"
            class="inline-flex items-center rounded-full px-2.5 py-1 text-xs font-medium"
            :class="[
              tag.isNew 
                ? 'bg-orange-100 text-orange-700 border border-orange-200' 
                : 'bg-slate-100 text-slate-700'
            ]"
          >
            {{ typeof tag === 'object' ? tag.name : tag }}
            <span v-if="tag.isNew" class="ml-1 text-orange-500 text-[10px]">(新)</span>
            <button 
              type="button" 
              class="ml-1 text-slate-500 hover:text-slate-700"
              @click="removeTag(tag)"
            >
              <XMarkIcon class="w-3.5 h-3.5" />
            </button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 特色图片上传 -->
    <div class="space-y-4">
      <div class="space-y-1">
        <h3 class="text-base font-medium text-slate-700 flex items-center">
          特色图片 <span class="text-rose-500 ml-1">*</span>
        </h3>
        <p class="text-sm text-slate-500">
          上传一张代表你文章内容的图片，它将显示在文章列表和社交媒体分享中。
        </p>
      </div>
      
      <div 
        class="border-2 border-dashed rounded-lg p-4 text-center"
        :class="[
          featuredImageUrl ? 'border-slate-200 bg-slate-50' : 'border-slate-300 bg-white hover:bg-slate-50'
        ]"
        @drop.prevent="handleDrop"
        @dragover.prevent
      >
        <div v-if="!featuredImageUrl" class="space-y-2 cursor-pointer" @click="openFilePicker">
          <div class="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-slate-100">
            <PhotoIcon class="w-6 h-6 text-slate-500" />
          </div>
          <div class="text-sm text-slate-500">
            <span class="font-medium text-slate-600 hover:text-slate-700">
              点击上传图片
            </span>
            <p>或拖放文件到此处</p>
          </div>
          <p class="text-xs text-slate-400">
            支持的格式: JPG, PNG, GIF，最大1MB
          </p>
        </div>
        
        <div v-else class="relative">
          <img 
            :src="featuredImageUrl" 
            alt="Featured image" 
            class="w-full h-48 object-cover rounded-md"
          />
          <div class="absolute inset-0 bg-slate-900 bg-opacity-50 opacity-0 hover:opacity-100 transition-opacity flex items-center justify-center rounded-md z-10">
            <button 
              type="button"
              class="p-2 rounded-full bg-white text-slate-600 hover:text-slate-800 mr-2 z-20"
              @click.stop="openFilePicker"
            >
              <PencilIcon class="w-5 h-5" />
            </button>
            <button 
              type="button"
              class="p-2 rounded-full bg-white text-slate-600 hover:text-red-500 z-20"
              @click.stop="removeFeaturedImage"
            >
              <TrashIcon class="w-5 h-5" />
            </button>
          </div>
        </div>
        
        <input 
          ref="fileInput"
          type="file"
          accept="image/*"
          class="hidden"
          @change="handleFileUpload"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue';
import { useArticleEditorStore } from '@/stores/articleEditor';
import { useToast } from '@/Composables/useToast';
import axios from 'axios';
import {
  CheckCircleIcon,
  MagnifyingGlassIcon,
  ChevronDownIcon,
  ArrowPathIcon,
  CheckIcon,
  PlusIcon,
  XMarkIcon,
  PhotoIcon,
  ArrowUpTrayIcon,
  PencilIcon,
  TrashIcon
} from '@heroicons/vue/20/solid';

const props = defineProps({
  categories: {
    type: Array,
    required: true
  },
  tags: {
    type: Array,
    required: true
  }
});

const editorStore = useArticleEditorStore();
const toast = useToast();

// 本地状态
const selectedCategoryId = ref(editorStore.categoryId);
const selectedTags = ref([...(editorStore.tags || [])]);
const tagSearchQuery = ref('');
const filteredTags = ref([]);
const allTags = ref([...(props.tags || [])]);
const activeTagIndex = ref(-1);
const showTagDropdown = ref(false);
const isUploading = ref(false);
const featuredImageUrl = ref(editorStore.featuredImageUrl || null);
const fileInput = ref(null);
const isSearchingTags = ref(false);
let searchTagsTimeout = null;

// 监听store变化
watch(() => editorStore.categoryId, (newId) => {
  selectedCategoryId.value = newId;
});

watch(() => editorStore.tags, (newTags) => {
  selectedTags.value = newTags;
});

watch(() => editorStore.featuredImageUrl, (newUrl) => {
  featuredImageUrl.value = newUrl;
});

// 监听props.tags变化，更新allTags
watch(() => props.tags, (newTags) => {
  allTags.value = [...(newTags || [])];
}, { immediate: true });

// 计算属性
const canCreateNewTag = computed(() => {
  if (!tagSearchQuery.value || tagSearchQuery.value.length < 2) return false;
  
  // 检查是否已存在相同名称的标签（包括已选择的标签）
  const query = tagSearchQuery.value.toLowerCase().trim();
  const existsInTags = allTags.value.some(tag => 
    tag.name.toLowerCase() === query
  );
  const existsInSelected = selectedTags.value.some(tag => {
    const tagName = typeof tag === 'object' ? tag.name : tag;
    return tagName.toLowerCase() === query;
  });
  
  return !existsInTags && !existsInSelected;
});

// 获取所有可用的标签（排除已选择的）
const availableTags = computed(() => {
  return allTags.value.filter(tag => !isTagSelected(tag.id));
});

// 分类选择
const selectCategory = (categoryId) => {
  selectedCategoryId.value = categoryId;
  editorStore.setCategory(categoryId);
};

// 获取分类图标（简单的emoji映射）
const getCategoryIcon = (category) => {
  const iconMap = {
    'technology': '💻',
    'programming': '👨‍💻',
    'design': '🎨',
    'marketing': '📊',
    'business': '💼',
    'lifestyle': '🌴',
    'health': '🏥',
    'food': '🍔',
    'travel': '✈️',
    'education': '📚',
    'entertainment': '🎭',
    'sports': '⚽',
    'news': '📰',
    'other': '📌'
  };
  
  // 默认图标
  let icon = '📝';
  
  // 通过分类名称或slug查找匹配的图标
  const categoryName = category.name.toLowerCase();
  const categorySlug = category.slug?.toLowerCase() || '';
  
  // 尝试匹配分类名或slug
  Object.keys(iconMap).forEach(key => {
    if (categoryName.includes(key) || categorySlug.includes(key)) {
      icon = iconMap[key];
    }
  });
  
  return icon;
};

// 标签搜索（从服务器端搜索）
const searchTags = async () => {
  const query = tagSearchQuery.value?.trim() || '';
  
  // 清除之前的定时器
  if (searchTagsTimeout) {
    clearTimeout(searchTagsTimeout);
  }
  
  if (!query) {
    filteredTags.value = [];
    activeTagIndex.value = -1;
    showTagDropdown.value = true; // 显示所有标签
    return;
  }
  
  showTagDropdown.value = true;
  
  // 防抖：延迟300ms后执行搜索
  searchTagsTimeout = setTimeout(async () => {
    isSearchingTags.value = true;
    
    try {
      // 从服务器端搜索标签
      const response = await axios.get('/api/tags', {
        params: {
          search: query
        }
      });
      
      const searchResults = response.data || [];
      
      // 过滤掉已选择的标签
      filteredTags.value = searchResults
        .filter(tag => {
          if (!tag || !tag.name) return false;
          return !selectedTags.value.some(st => {
            const stId = typeof st === 'object' ? st.id : st;
            return stId === tag.id;
          });
        })
        .slice(0, 10); // 最多显示10个建议
      
      // 重置激活索引
      activeTagIndex.value = filteredTags.value.length > 0 ? 0 : -1;
    } catch (error) {
      console.error('搜索标签失败:', error);
      // 如果搜索失败，回退到本地搜索
      const queryLower = query.toLowerCase();
      filteredTags.value = allTags.value
        .filter(tag => {
          if (!tag || !tag.name) return false;
          const tagName = tag.name.toLowerCase();
          const isNotSelected = !selectedTags.value.some(st => {
            const stId = typeof st === 'object' ? st.id : st;
            return stId === tag.id;
          });
          return tagName.includes(queryLower) && isNotSelected;
        })
        .slice(0, 10);
      
      activeTagIndex.value = filteredTags.value.length > 0 ? 0 : -1;
    } finally {
      isSearchingTags.value = false;
    }
  }, 300);
};

// 处理输入框失焦
const handleInputBlur = () => {
  // 延迟关闭下拉列表，以便点击事件能够触发
  setTimeout(() => {
    showTagDropdown.value = false;
  }, 200);
};

// 处理标签输入（回车）
const handleTagEnter = (event) => {
  event.preventDefault();
  
  const query = tagSearchQuery.value?.trim() || '';
  
  // 如果有搜索内容
  if (query) {
    // 优先选择匹配的标签（如果有）
    if (filteredTags.value.length > 0 && activeTagIndex.value >= 0 && activeTagIndex.value < filteredTags.value.length) {
      addTag(filteredTags.value[activeTagIndex.value]);
    } 
    // 如果激活索引指向创建新标签选项
    else if (canCreateNewTag.value && activeTagIndex.value === filteredTags.value.length) {
      createTag();
    }
    // 如果没有匹配的标签，但可以创建新标签，则创建
    else if (canCreateNewTag.value) {
      createTag();
    }
  } 
  // 如果输入框为空，选择当前激活的标签或显示所有标签
  else {
    if (availableTags.value.length > 0 && activeTagIndex.value >= 0 && activeTagIndex.value < availableTags.value.length) {
      addTag(availableTags.value[activeTagIndex.value]);
    } else {
      showTagDropdown.value = true;
    }
  }
};

// 处理标签导航（上下箭头键）
const handleTagNavigation = (direction, event) => {
  if (event) {
    event.preventDefault();
  }
  
  showTagDropdown.value = true;
  
  // 计算总选项数（包括创建新标签选项）
  let totalOptions;
  if (tagSearchQuery.value?.trim()) {
    // 有搜索内容时，包括筛选结果和创建新标签选项
    totalOptions = filteredTags.value.length + (canCreateNewTag.value ? 1 : 0);
  } else {
    // 没有搜索内容时，显示所有未选择的标签
    totalOptions = availableTags.value.length;
  }
  
  if (totalOptions === 0) {
    activeTagIndex.value = -1;
    return;
  }
  
  // 如果当前索引无效，初始化为0或最后一个
  if (activeTagIndex.value < 0) {
    activeTagIndex.value = direction > 0 ? 0 : totalOptions - 1;
  } else {
    activeTagIndex.value += direction;
  }
  
  // 循环导航
  if (activeTagIndex.value < 0) {
    activeTagIndex.value = totalOptions - 1;
  } else if (activeTagIndex.value >= totalOptions) {
    activeTagIndex.value = 0;
  }
};

// 检查标签是否已选择
const isTagSelected = (tagId) => {
  if (!tagId) return false;
  return selectedTags.value.some(tag => {
    // 已有标签：通过 id 判断
    if (tag.id === tagId) return true;
    return false;
  });
};

// 切换标签选择状态
const toggleTag = (tag) => {
  if (isTagSelected(tag.id)) {
    removeTag(tag.id);
  } else {
    addTag(tag);
  }
};

// 添加标签
const addTag = (tag) => {
  // 检查是否已选择（支持已有标签和新标签）
  const isSelected = selectedTags.value.some(t => {
    // 已有标签：通过 id 判断
    if (tag.id && t.id === tag.id) return true;
    // 新标签：通过 name 判断（不区分大小写）
    const tagName = typeof tag === 'object' ? tag.name : tag;
    const tName = typeof t === 'object' ? t.name : t;
    return tagName && tName && tagName.toLowerCase() === tName.toLowerCase();
  });
  
  if (!isSelected) {
    selectedTags.value.push(tag);
    editorStore.addTag(tag);
    tagSearchQuery.value = '';
    filteredTags.value = [];
    activeTagIndex.value = -1;
    showTagDropdown.value = false;
  }
};

// 移除标签
const removeTag = (tag) => {
  // 从本地状态中移除
  selectedTags.value = selectedTags.value.filter(t => {
    // 已有标签：通过 id 判断
    if (tag.id && t.id === tag.id) return false;
    // 新标签：通过 name 判断（不区分大小写）
    const tagName = typeof tag === 'object' ? tag.name : tag;
    const tName = typeof t === 'object' ? t.name : t;
    if (tagName && tName && tagName.toLowerCase() === tName.toLowerCase()) return false;
    return true;
  });
  
  // 从store中移除
  if (tag.id) {
    editorStore.removeTag(tag.id);
  } else {
    // 新标签通过名称移除
    const tagName = typeof tag === 'object' ? tag.name : tag;
    editorStore.removeTag(tagName);
  }
};

// 创建新标签（临时创建，不立即保存到数据库）
const createTag = () => {
  const tagName = tagSearchQuery.value?.trim();
  if (!tagName || tagName.length < 2) return;
  
  // 创建一个临时标签对象（只有 name，没有 id）
  // 提交时由后端统一处理创建
  const tempTag = {
    name: tagName,
    isNew: true // 标记为新标签
  };
  
  addTag(tempTag);
  toast.success(`标签 "${tagName}" 已添加，将在提交时创建`);
};

// 特色图片处理
const openFilePicker = () => {
  if (fileInput.value) {
    fileInput.value.click();
  }
};

const handleFileUpload = async (event) => {
  const file = event.target.files[0];
  if (!file) return;
  
  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    toast.error('请上传图片文件');
    return;
  }
  
  // 验证文件大小（1MB = 1024 * 1024 bytes）
  if (file.size > 1024 * 1024) {
    toast.error('图片大小不能超过 1MB');
    return;
  }
  
  await uploadImage(file);
};

const handleDrop = (event) => {
  const file = event.dataTransfer.files[0];
  if (!file) return;
  
  if (!file.type.startsWith('image/')) {
    toast.error('请上传图片文件');
    return;
  }
  
  if (file.size > 1024 * 1024) {
    toast.error('图片大小不能超过 1MB');
    return;
  }
  
  uploadImage(file);
};

const uploadImage = async (file) => {
  isUploading.value = true;
  
  try {
    const formData = new FormData();
    formData.append('image', file);
    
    const response = await axios.post('/author/upload/image', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    
    featuredImageUrl.value = response.data.url;
    editorStore.setFeaturedImageUrl(response.data.url);
    
    toast.success('特色图片上传成功');
  } catch (error) {
    console.error('特色图片上传失败', error);
    const errorMessage = error.response?.data?.message || error.response?.data?.error || '未知错误';
    toast.error('特色图片上传失败: ' + errorMessage);
  } finally {
    isUploading.value = false;
    // 清空文件输入，允许重复上传同一文件
    if (fileInput.value) {
      fileInput.value.value = '';
    }
  }
};

const removeFeaturedImage = () => {
  featuredImageUrl.value = null;
  editorStore.setFeaturedImageUrl(null);
  
  // 清空文件输入
  if (fileInput.value) {
    fileInput.value.value = '';
  }
};
</script>

<style scoped>
.category-tag-selector {
  display: flex;
  flex-direction: column;
  gap: 2rem;
  width: 100%;
}

.section {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.section-title {
  font-size: 1.25rem;
  font-weight: 600;
  color: #111827;
}

.section-description {
  font-size: 0.875rem;
  color: #6b7280;
  margin-bottom: 0.5rem;
}

.required {
  color: #ef4444;
}

.optional {
  color: #6b7280;
  font-size: 0.875rem;
  font-weight: 400;
}

/* 分类选择 */
.category-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 0.75rem;
}

.category-item {
  display: flex;
  align-items: center;
  padding: 0.75rem;
  background-color: #f9fafb;
  border: 1px solid #e5e7eb;
  border-radius: 0.5rem;
  cursor: pointer;
  transition: all 0.2s ease;
}

.category-item:hover {
  background-color: #f3f4f6;
  border-color: #d1d5db;
}

.category-item.selected {
  background-color: #eff6ff;
  border-color: #3b82f6;
}

.category-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 2.5rem;
  height: 2.5rem;
  background-color: #e5e7eb;
  border-radius: 0.5rem;
  margin-right: 0.75rem;
  font-size: 1.5rem;
}

.category-info {
  flex: 1;
}

.category-name {
  font-weight: 500;
  color: #1f2937;
}

.category-count {
  font-size: 0.75rem;
  color: #6b7280;
}

.check-icon {
  color: #3b82f6;
}

/* 标签选择 */
.tag-search-container {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.search-input-container {
  position: relative;
}

.tag-search-input {
  width: 100%;
  padding: 0.75rem;
  background-color: #f9fafb;
  border: 1px solid #e5e7eb;
  border-radius: 0.375rem;
  font-size: 0.875rem;
  color: #1f2937;
  transition: all 0.2s ease;
}

.tag-search-input:focus {
  outline: none;
  border-color: #3b82f6;
  background-color: #ffffff;
}

.create-tag-button {
  position: absolute;
  right: 0.5rem;
  top: 50%;
  transform: translateY(-50%);
  padding: 0.25rem 0.5rem;
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 0.25rem;
  font-size: 0.75rem;
  cursor: pointer;
  transition: all 0.2s ease;
}

.create-tag-button:hover {
  background-color: #2563eb;
}

.selected-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
}

.tag-badge {
  display: flex;
  align-items: center;
  padding: 0.25rem 0.5rem;
  background-color: #eff6ff;
  border: 1px solid #bfdbfe;
  border-radius: 9999px;
  font-size: 0.75rem;
  color: #1e40af;
}

.remove-tag-button {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 0.25rem;
  color: #3b82f6;
  background: transparent;
  border: none;
  cursor: pointer;
}

.tag-suggestions {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 0.5rem;
  margin-top: 0.5rem;
}

.tag-suggestion-item {
  padding: 0.5rem;
  background-color: #f9fafb;
  border: 1px solid #e5e7eb;
  border-radius: 0.375rem;
  font-size: 0.75rem;
  color: #4b5563;
  cursor: pointer;
  transition: all 0.2s ease;
}

.tag-suggestion-item:hover {
  background-color: #f3f4f6;
  border-color: #d1d5db;
}

.tag-suggestion-item.selected {
  background-color: #eff6ff;
  border-color: #3b82f6;
  color: #1e40af;
}

.tag-count {
  font-size: 0.7rem;
  color: #6b7280;
}

/* 封面图 */
.featured-image-container {
  width: 100%;
}

.hidden-input {
  display: none;
}

.image-upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 2rem;
  border: 2px dashed #e5e7eb;
  border-radius: 0.5rem;
  background-color: #f9fafb;
  cursor: pointer;
  transition: all 0.2s ease;
}

.image-upload-area:hover {
  background-color: #f3f4f6;
  border-color: #d1d5db;
}

.upload-icon {
  margin-bottom: 1rem;
  color: #9ca3af;
}

.upload-text {
  font-weight: 500;
  color: #4b5563;
  margin-bottom: 0.5rem;
}

.upload-hint {
  font-size: 0.75rem;
  color: #9ca3af;
}

.image-preview {
  position: relative;
  border-radius: 0.5rem;
  overflow: hidden;
}

.preview-image {
  width: 100%;
  height: auto;
  max-height: 400px;
  object-fit: cover;
}

.image-actions {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 0.75rem;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: flex-end;
}

.remove-image-button {
  display: flex;
  align-items: center;
  padding: 0.25rem 0.5rem;
  background-color: #ef4444;
  color: white;
  border: none;
  border-radius: 0.25rem;
  font-size: 0.75rem;
  cursor: pointer;
  transition: all 0.2s ease;
}

.remove-image-button:hover {
  background-color: #dc2626;
}

/* 深色模式 */
:deep(.dark-mode) .section-title {
  color: #f3f4f6;
}

:deep(.dark-mode) .section-description {
  color: #9ca3af;
}

:deep(.dark-mode) .category-item {
  background-color: #1f2937;
  border-color: #374151;
}

:deep(.dark-mode) .category-item:hover {
  background-color: #374151;
  border-color: #4b5563;
}

:deep(.dark-mode) .category-item.selected {
  background-color: #1e3a8a;
  border-color: #3b82f6;
}

:deep(.dark-mode) .category-name {
  color: #f3f4f6;
}

:deep(.dark-mode) .category-count {
  color: #9ca3af;
}

:deep(.dark-mode) .tag-search-input {
  background-color: #1f2937;
  border-color: #374151;
  color: #f3f4f6;
}

:deep(.dark-mode) .tag-search-input:focus {
  border-color: #3b82f6;
  background-color: #111827;
}

:deep(.dark-mode) .tag-suggestion-item {
  background-color: #1f2937;
  border-color: #374151;
  color: #d1d5db;
}

:deep(.dark-mode) .tag-suggestion-item:hover {
  background-color: #374151;
  border-color: #4b5563;
}

:deep(.dark-mode) .image-upload-area {
  background-color: #1f2937;
  border-color: #374151;
}

:deep(.dark-mode) .image-upload-area:hover {
  background-color: #374151;
  border-color: #4b5563;
}

:deep(.dark-mode) .upload-text {
  color: #d1d5db;
}

/* 移动适配 */
@media (max-width: 640px) {
  .category-grid {
    grid-template-columns: 1fr;
  }
  
  .tag-suggestions {
    grid-template-columns: 1fr 1fr;
  }
}
</style> 